#include  "PressAndHoldButton.h"


// constructor based on a GenericButton (period defaults to 0.05)
PressAndHoldButton::PressAndHoldButton(GenericButton *button, float period)
{
	m_button = button;
	Init(period);
}


// initialize member variables, start Notifier
void PressAndHoldButton::Init(float period)
{
	m_controlLoop = new Notifier(PressAndHoldButton::CallUpdate, this);
	
	m_enabled = false;
	
	m_pressed = false;
	m_number_of_samples = 1;
	
	m_controlLoop->StartPeriodic(period);
}

// set the time (in seconds) between samples
void PressAndHoldButton::SetSampleRate(float period)
{
	m_controlLoop->Stop();
	m_controlLoop->StartPeriodic(period);
}


// set how many samples the button must be held down to be considered pressed
void PressAndHoldButton::SetNeededSamples(int number_of_samples)
{
	m_number_of_samples = number_of_samples;
}

/*
 * Call the Update method as a non-static method.
 * Do fancy stuff to setup the "this" pointer
 */
void PressAndHoldButton::CallUpdate(void *ob)
{
	PressAndHoldButton *button_ob = (PressAndHoldButton*) ob;
	button_ob->Update();
}

// has the button been pressed for the specefied amount?
bool PressAndHoldButton::Get()
{
	return m_pressed;
}

// this function is called periodically to monitor the status of the button and act accordingly
void PressAndHoldButton::Update()
{
	//printf("update called\n");
	if (m_enabled)
	{
		if (m_button->Get())
		{
			m_count++;
		}
		else
		{
			m_count = 0;
			m_pressed = false;
		}
		
		if (m_count >= m_number_of_samples && !m_pressed)
		{
			printf("I got %d presses in a row: Consider yourself press'd\n", m_count);
			m_pressed = true;
		}
			
	}	
}

// enable the button (it now responds to button pushes)
void PressAndHoldButton::Enable()
{
	m_enabled = true;
}

// disable the button (it now ignores button pushes)
void PressAndHoldButton::Disable()
{
	m_enabled = false;
}
